package yuhuibear.poat.object.mapEntity;

import java.util.Iterator;
import java.util.Map.Entry;

import yuhuibear.poat.annotations.relation.Field;
import yuhuibear.poat.annotations.relation.Table;
import yuhuibear.poat.object.bean.AttributeMapper;
import yuhuibear.poat.object.bean.BeanStruct;

public class TableTask extends SqlTask {

	private final static String REF = "references ";

	private static int tableCnt = 0;

	public TableTask(BeanStruct bean) {
		init(bean.getDBName(), MapEntityTask.Type.Table, bean.getType().toString(), bean, createTableSQL(bean));

		TableTask.tableCnt++;
		SqlTask.register();
	}

	public void done() {
		done = true;
		TableTask.tableCnt--;
		SqlTask.unRegister();
	}

	public static int tableCount() {
		return tableCnt;
	}

	private void parseReferences(String constrain, String except) {
		int idx = constrain.indexOf(REF);
		if (idx < 0)
			return;
		idx = idx + REF.length();
		int iend = constrain.indexOf('(', idx);
		String refName = constrain.substring(idx, iend);
		if (refName != null) {
			refName = refName.trim();
			if (refName.length() > 0 && !refName.equals(except))
				refs.add(refName);
		}
	}

	private String createTableSQL(BeanStruct dscp) {
		String sql = null;
		Table table = dscp.getAnnotation(Table.class);
		Iterator<Entry<String, AttributeMapper>> itr = dscp.getAttributes().entrySet().iterator();
		String atrs = "";
		while (itr.hasNext()) {
			AttributeMapper atrbMapper = itr.next().getValue();
			Field attribute = atrbMapper.getAnnotation(Field.class);
			if (attribute == null) {
				continue;
			}
			atrs = atrs + attribute.name().trim() + " "
					+ attribute.type().trim() + " "
					+ attribute.constrain().trim() + ", ";
			parseReferences(attribute.constrain(), dscp.getDBName());
		}
		if (atrs.length() < 1)
			return sql;
		if (table.constrain().trim().length() > 0) {
			atrs = atrs + table.constrain().trim();
		}
		else {
			atrs = atrs.substring(0, atrs.length() - 2);
		}
		sql = "create table " + table.name().trim() + " ( " + atrs + " )";
		return sql;
	}

}
